<template>
  <div class="user">
    <el-card style="width:98%;margin:30px auto;">
      <div clas="title" style="font-weight:bold;font-size:17px">用户管理</div>
      <div style="display: flex;justify-content: space-between">
        <!--插入和批量删除-->
        <div style="margin: 20px 2px">
          <el-button type="primary" icon="el-icon-plus" circle @click="addOpen" title="添加"></el-button>
          <el-button type="danger" @click="delBatch" icon="el-icon-delete" title="批量删除" slot="reference"
                     style="margin-left: 10px"></el-button>
        </div>
        <!--模糊查询-->
        <div style="margin: 20px 5px">
          <el-input style="width: 200px" placeholder="请输入用户名" suffix-icon="el-icon-search"
                    v-model.trim="username"></el-input>
          <el-input style="width: 200px;margin-left: 5px" placeholder="请输入昵称" suffix-icon="el-icon-search"
                    v-model.trim="nickname"></el-input>
          <el-input style="width: 200px;margin-left: 5px" placeholder="请输入家庭住址" suffix-icon="el-icon-search"
                    v-model.trim="address"></el-input>
          <el-button class="ml-5" type="primary" style="margin-left: 10px" @click="load">搜索</el-button>
          <el-button type="warning" @click="reset">重置</el-button>
        </div>


      </div>
      <!--表格渲染-->
      <el-table :data="tableData" border stripe :header-cell-class-name="'headerBg'"
                @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <!--<el-table-column prop="id" label="ID" width="80"></el-table-column>-->
        <el-table-column
          prop="username"
          label="用户名"
          align="center"
        >

        </el-table-column>
        <el-table-column prop="nickname" label="昵称"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <!--<el-table-column prop="age" label="年龄" width="80" align="center"></el-table-column>-->
        <el-table-column prop="sex" label="性别" width="80" align="center">
        </el-table-column>
        <el-table-column prop="address" label="家庭住址"></el-table-column>
        <el-table-column prop="role" label="角色" width="100" align="center">
          <template slot-scope="scope">
            <el-tag type="primary" v-if="scope.row.role === 'ROLE_ADMIN'">超级用户</el-tag>
            <el-tag type="primary" v-if="scope.row.role === 'ROLE_ROOT'">管理员</el-tag>
            <el-tag type="warning" v-if="scope.row.role === 'ROLE_USER'">普通用户</el-tag>
            <el-tag type="success" v-if="scope.row.role === 'ROLE_TEST'">测试用户</el-tag>
            <el-tag type="success" v-if="scope.row.role === 'ROLE_TOURIST'">游客</el-tag>
          </template>
        </el-table-column>
        <!--<el-table-column prop="birthday" label="破壳日" :formatter="dateFormat" width="100"></el-table-column>-->
        <el-table-column prop="points" label="积分" width="80" align="center"></el-table-column>


        <el-table-column label="操作" width="150" align="center">

          <template slot-scope="scope">

            <el-button type="info" icon="el-icon-message" @click="look(scope.row)" circle title="详细信息"></el-button>
            <el-button type="primary" @click="edit(scope.row)" icon="el-icon-edit" circle></el-button>

            <el-button @click="del(scope.row.id)" title="删除"
                       slot="reference" type="danger" icon="el-icon-delete" circle
                       style="margin-left: 10px"></el-button>

          </template>
        </el-table-column>
      </el-table>


      <!--分页-->
      <div style="padding: 10px 0">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[2, 5, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
    <!--弹窗-->
    <el-dialog title="用户信息" :visible.sync="addDialogVisible"  :destroy-on-close="true">
      <el-form label-width="80px" size="small" ref="form" :rules="rules" :model="form">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select clearable v-model="form.role" placeholder="请选择角色" style="width: 100%">
            <el-option v-for="item in roles" :key="item.name" :label="item.name" :value="item.flag"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="破壳日" prop="birthday">
          <el-date-picker
            v-model="form.birthday"
            type="date"
            placeholder="选择日期"
            format="yyyy 年 MM 月 dd 日">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="年龄" prop="age">
          <el-select v-model="form.age" placeholder="请选择" filterable>
            <el-option
              v-for="item in 100"
              :key="item"
              :label="item"
              :value="item">
            </el-option>
          </el-select>

        </el-form-item>
        <el-form-item label="性别" prop="age">
          <el-radio-group v-model="form.sex">
            <el-radio label="男"></el-radio>
            <el-radio label="女"></el-radio>
            <el-radio label="未知"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input type="textarea" v-model="form.address" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('form')">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>

    <!--查看弹窗-->

    <el-dialog title="详细信息" :visible.sync="lookDialogVisible" :destroy-on-close="true">
      <el-form label-width="80px" size="small" ref="form" :model="form">
        <el-form-item label="头像:">

          <el-image
            style="width: 120px; height: 120px;margin-left:150px;"
            :src="form.avatar">
          </el-image>
        </el-form-item>

        <el-form-item label="用户名:">
          {{ form.username }}
        </el-form-item>
        <el-form-item label="角色:" >

            <el-tag type="primary" v-if="form.role === 'ROLE_ADMIN'">超级用户</el-tag>
            <el-tag type="primary" v-if="form.role === 'ROLE_ROOT'">管理员</el-tag>
            <el-tag type="warning" v-if="form.role === 'ROLE_USER'">普通用户</el-tag>
            <el-tag type="success" v-if="form.role === 'ROLE_TEST'">测试用户</el-tag>
            <el-tag type="success" v-if="form.role === 'ROLE_TOURIST'">游客</el-tag>

        </el-form-item>
        <el-form-item label="昵称:" prop="nickname">
          {{ form.nickname }}
        </el-form-item>
        <el-form-item label="邮箱:" prop="email">
          {{ form.email }}
        </el-form-item>
        <el-form-item label="破壳日:" prop="birthday" :formatter="dateFormat">
          {{ form.birthday }}
        </el-form-item>

        <el-form-item label="年龄:" prop="age">
          {{ form.age }}

        </el-form-item>
        <el-form-item label="性别:" prop="age">
          {{ form.sex }}
        </el-form-item>
        <el-form-item label="地址:" prop="address">
          {{ form.address }}
        </el-form-item>
        <el-form-item label="积分:" prop="address">
          {{ form.points }}
        </el-form-item>
      </el-form>

    </el-dialog>

  </div>
</template>

<script>
import {serverIp} from '../../../public/config';
import {dateFormat} from '../../assets/js/dateFormat'

export default {
  name: "Index",

  data() {
    return {
      loading: true,
      dateFormat: dateFormat,
      username: '',
      nickname: '',
      address: '',
      dialogVisible1: false,
      rules: {
        username: [
          {required: true, message: '请填写用户名', trigger: 'blur'},
          // {min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur'}
        ],
        nickname: [
          {required: true, message: '请输入昵称', trigger: 'blur'},
          {min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur'}
        ],
        role: [
          {required: true, message: '请选择角色', trigger: 'blur'},

        ],
      },
      form: {},
      addDialogVisible: false,
      serverIp: serverIp,

      tableData: [],
      multipleSelection: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      roles: [],
      lookDialogVisible: false

    }
  },
  created() {
    this.load()
    this.request.get("/role").then(res => {
      this.roles = res.data
    })
  },
  methods: {

    //新增
    save() {

      this.$refs['form'].validate((valid) => {
        if (valid) {  // 表单校验合法
          this.request.post("/user", this.form).then(res => {
            if (res.code === 200) {
              this.$message.success("保存成功")
              this.addDialogVisible = false
              this.load()
            } else {
              this.$message.error("保存失败")
            }
          })
        }
      })

    },
    resetForm() {
      this.$nextTick(() => {
        this.$refs.form.resetFields();
      })

      this.addDialogVisible = false

    },
    //添加弹窗
    addOpen() {
      this.addDialogVisible = true
      this.form = {}
    },


//编辑弹窗
    edit(row) {
      this.form = JSON.parse(JSON.stringify(row))
      this.addDialogVisible = true
    },

    //详细消息弹窗
    look(row) {
      this.form = JSON.parse(JSON.stringify(row))
      console.log(this.form)

      this.lookDialogVisible = true
    },


    //初始化分页
    load() {
      this.request.get("/user/selectPage", {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          nickname: this.nickname,
          username: this.username,
          address: this.address,
        }
      }).then(res => {

        this.tableData = res.data.records
        this.total = res.data.total

      })
    },


    //根据id进行删除
    del(id) {
      this.$confirm('你确定要删除,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        customClass: 'msgbox',
        type: 'warning'
      }).then(async () => {
        this.request.delete("/user/" + id).then(res => {
          if (res.code === 200) {
            this.$message({message: '删除成功', type: "success"})
            this.load()
          } else {
            this.$message({message: '删除失败', type: "error"})
          }
        })
      }).catch(() => {
        this.$message({
          message: '已取消删除',
          type: 'success'
        })
      })
    },

    //多选框
    handleSelectionChange(val) {
      this.multipleSelection = val

    },

    //批量删除
    delBatch() {
      this.$confirm('你确定要批量删除,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        customClass: 'msgbox',
        type: 'warning'
      }).then(async () => {
        let ids = this.multipleSelection.map(v => v.id)  // [{}, {}, {}] => [1,2,3]
        this.request.post("/user/del/batch", ids).then(res => {
          if (ids.length === 0) {
            this.$message({
              type: 'warning',
              message: '请选择数据!'
            });
            return
          }

          if (res.code === 200) {
            this.$message({message: '批量删除成功', type: "success"})
            this.load()
          } else {
            this.$message({message: '批量删除失败', type: "error"})
          }
        })
      }).catch(() => {
        this.$message({
          message: '已取消删除',
          type: 'success'
        })
      })
    },

    //重置
    reset() {
      this.username = ""
      this.nickname = ""
      this.address = ""
      this.load()
    },

    //当前页面的个数
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.load()
    },

    //当前页面从哪里开始
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum
      this.load()
    },


  }
}
</script>

<style lang="scss" scope>



.user{

  .title {
    position: absolute;
    left: 0;
    font-size: 16px;
    font-weight: bold;
    color: #202a34;
  }

  .title::before {
    content: '';
    width: 24px;
    height: 16px;
    border-left: 3px solid #0081ff;
    margin-right: 20px;
  }
  .el-dialog {
    width: 30%;
  }


  @media screen and (max-width: 440px) {
    .el-dialog {
      width: 90%;
    }

    @media only screen and (min-width:600px) and (max-width:1200px){
      .el-dialog {
        width: 60%;
      }
    }

    @media only screen and (min-width:441px) and (max-width:599px){
      .el-dialog {
        width: 80%;
      }
    }
  }
}

</style>

<style >

@media (max-width: 720px) {
  .msgbox{
    width: 327px !important;
  }
}

</style>
